<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 栅格布局 -->
      <el-row :gutter="30">
        <el-col :span="8"><div style="margin-top: 15px;">
          <el-input  clearable @clear="getUserList" placeholder="请输入内容" class="input-with-select" v-model="queryData.query">
            <el-button slot="append" icon="el-icon-search"  @click="getUserList"></el-button>
          </el-input>
        </div>
        </el-col>
        <el-col :span="4"><el-button type="primary" @click="addDialogVisible = true" >添加用户</el-button></el-col>
      </el-row>
      <!-- 用户表格 -->
      <el-table
      :data="users"
      border
      stripe
      >
        <el-table-column type='index' width="50px" lable="#" ></el-table-column>
        <!-- <el-table-column prop="item.prop" :label="item.label" v-for="(item, index) in userAttrList" :key="index"></el-table-column> -->
        <el-table-column prop="username" label="姓名" ></el-table-column>
        <el-table-column prop="email" label="邮箱" ></el-table-column>
        <el-table-column prop="mobile" label="电话" ></el-table-column>
        <el-table-column prop="role_name" label="角色" ></el-table-column>
        <el-table-column  label="状态" >
          <template slot-scope="scope">
          <el-switch
            @change="switchChange(scope.row)"
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="操作" width="180px" >
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" :enterable="false"  placement="top-start">
                <el-button @click="editUser(scope.row)"  type="primary" icon="el-icon-edit" size="mini"></el-button>
            </el-tooltip>
            <el-tooltip  class="item" effect="dark" content="删除" :enterable="false"  placement="top-start">
               <el-button  type="danger" @click="delUser(scope.row)"  icon="el-icon-delete" size="mini"></el-button>
             </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" :enterable="false"  placement="top-start">
              <el-button type="warning" @click="roleAssignment(scope.row)" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryData.pagenum"
            :page-sizes="[2, 4, 6, 10]"
            :page-size="queryData.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="resetForm"
     >
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-form  ref="addUserForm"  :rules="addUserFormRules" :model="addUserForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
           <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addUserForm.password"></el-input>
          </el-form-item>
           <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
           <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑信息"
      :visible.sync="editDialogVisible"
      @close="resetEditForm"
      width="50%">
      <el-form ref="editUserForm" :model="editUserFormData" label-width="80px" :rules="editUserFormRules">
        <el-form-item label="用户名:">
          <el-input disabled v-model="editUserFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="editUserFormData.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="editUserFormData.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色分配对话框 -->
    <el-dialog
      title="角色分配"
      @close="removeRole"
      :visible.sync="roleDialogVisible"
      width="30%">
      <p>当前用户 : {{UserNameInfo.username}}</p>
      <p>当前角色 : {{UserNameInfo.role_name}}</p>
      <el-select v-model="selectVal" placeholder="请选择">
        <!-- label 显示的数据    :value需要传递给双向数据绑定的数据 这里需要存放获取过来的角色的id -->
        <el-option
          v-for="item in RolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'user',
  data () {
    // 邮箱的校验规则
    const checkEmail = (rule, value, cb) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) return cb()
      cb(new Error('请输入正确的邮箱'))
    }
    // 手机号验证规则
    const chexkMobile = (rule, value, cb) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) return cb()
      cb(new Error('手机号不合法'))
    }
    return {
      queryData: {
        query: '',
        // 默认显示第几页
        pagenum: 1,
        // 一页显示几个
        pagesize: 2
      },
      users: [],
      total: 0,
      userAttrList: [
        {
          prop: 'username',
          label: '姓名'
        },
        {
          prop: 'email',
          label: '邮箱'
        },
        {
          prop: 'mobile',
          label: '电话'
        },
        {
          prop: 'role_name',
          label: '角色'
        },
        {
          prop: 'mg_status',
          label: '状态'
        },
        {
          prop: 'date',
          label: '操作'
        }
      ],
      // 添加 用户对话框flag
      addDialogVisible: false,
      // 编辑对话框 flag
      editDialogVisible: false,
      // 删除对话框 flag
      delDialogVisible: false,
      // 角色分配对话框 flag
      roleDialogVisible: false,
      // 添加用户整个表单对象
      addUserForm: {
        username: 'admin',
        password: '123123',
        email: 'admin@example.com',
        mobile: '18888888888'
      },
      // 添加表单校验规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: chexkMobile, trigger: 'blur' }
        ]
      },
      // 编辑表单的数据
      editUserFormData: {
        username: 'mm',
        mobile: '18888888888',
        email: 'email@email.com'
      },
      // 编辑表单的校验规则
      editUserFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: chexkMobile, trigger: 'blur' }
        ]
      },
      // 角色分配的当前角色和用户名
      UserNameInfo: '',
      // 角色下拉框宽度
      formLabelWidth: '0',
      // 定义角色下拉框数据
      RolesList: [],
      // select下拉框双向绑定的数据
      selectVal: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取左侧列表
    async getUserList () {
      const { data: res } = await this.$axios.get('users', {
        params: this.queryData
      })
      if (res.meta.status !== 200) return res.$message.error('获取数据失败')
      this.users = res.data.users
      this.total = res.data.total
    },
    // 一页显示几个
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getUserList()
    },
    // 现实第几页
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUserList()
    },
    // 设置状态
    async switchChange (switchVal) {
      // 发起请求
      const { data: res } = await this.$axios.put(`users/${switchVal.id}/state/${switchVal.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        switchVal.mg_state = !switchVal.mg_state
        this.$message.error('设置用户状态失败')
        return
      }
      this.$message.success('设置用户状态成功')
    },
    // 重置添加用户表单
    resetForm () {
      this.$refs.addUserForm.resetFields()
    },
    // 添加用户请求
    subForm () {
      this.$refs.addUserForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        // 判断是否添加成功
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        // 成功后的逻辑
        this.$message.success('添加用户成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 关闭编辑用户对话框 重置里面的内容
    resetEditForm () {
      this.$refs.editUserForm.resetFields()
    },
    // 点击用户信息填充编辑对话框
    editUser (formData) {
      this.editUserFormData = formData
      this.editDialogVisible = true
    },
    // 发起请求修改用户
    editUserData () {
      this.$refs.editUserForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put(`users/${this.editUserFormData.id}`, {
          email: this.editUserFormData.email,
          mobile: this.editUserFormData.mobile
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改信息成功')
        this.getUserList()
        this.editDialogVisible = false
      })
    },
    // 点击打开删除对话框
    delUser (delVal) {
      this.$messageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`users/${delVal.id}`)
        if (res.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除成功!')
        this.getUserList()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 点击打开角色分配对话框
    async roleAssignment (roleVal) {
      this.roleDialogVisible = true
      this.UserNameInfo = roleVal
      const { data: res } = await this.$axios.get('roles')
      this.RolesList = res.data
    },
    // 分配角色
    async allotRoles () {
      if (this.selectVal === '') return this.$message.error('未选择任何角色')
      const { data: res } = await this.$axios.put(`users/${this.UserNameInfo.id}/role`, { rid: this.selectVal })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.roleDialogVisible = false
    },
    // 关闭时清空上一次选中值
    removeRole () {
      this.selectVal = ''
    }
  }
}
</script>

<style scoped lang="less">
.el-button{
  // background-color: rgb(0, 183, 255);
  margin-top: 15px;
}
.el-dialog p{
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: 600;
  color: rgb(184, 6, 6);
}

</style>
